package com.lanju.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.lanju.common.SnowflakeIdWorker;
import com.lanju.entity.Entrust;
import com.lanju.entity.HouseEntrustImg;
import com.lanju.entity.User;
import com.lanju.model.ResultModel;
import com.lanju.service.HouseEntrustService;
import com.lanju.service.HouseService;
import com.lanju.service.JedisService;
import com.lanju.service.UserService;
import com.lanju.util.ServletUtil;

@Controller
@RequestMapping("/houseEntrust")
public class HouseEntrustController {
	private static final Logger LOGGER = LoggerFactory.getLogger(HouseEntrustController.class);
    
    @Autowired
    HouseEntrustService entrustService;
    
    @Autowired
    HouseService houseService;
    @Resource
	JedisService jedisService;
    @Autowired
    UserService userService;
    
    @RequestMapping("/add")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public ResultModel add(HttpServletRequest request, HttpServletResponse response,HttpSession session){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
		Entrust entrust = json.toJavaObject(Entrust.class);
		User user =(User) session.getAttribute("userModel");
		entrust.setUserId(user.getUserId());
		entrust.setCreator(user.getUserId());
		entrust.setHouseId(UUID.randomUUID().toString());
		entrust.setCreateTime(new Date());
		entrust.setUpdateTime(new Date());
        return  entrustService.add(entrust,request,response);
    }
    
    
    @RequestMapping("/del")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public ResultModel del(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
		Entrust entrust = json.toJavaObject(Entrust.class);
        return  entrustService.del(entrust);
    }
    
    
    @RequestMapping("/edit")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public ResultModel edit(HttpServletRequest request, HttpServletResponse response,HttpSession session){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
		Entrust entrust = json.toJavaObject(Entrust.class);
		User user =(User) session.getAttribute("userModel");
		entrust.setUpdator(user.getUserId());
		entrust.setUpdateTime(new Date());
        return  entrustService.edit(entrust);
    }
    
    @RequestMapping("/updateEntrustType")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Map<String,Object> updateEntrustType(HttpServletRequest request, HttpServletResponse response,HttpSession session){
    	Map<String, Object> param = ServletUtil.getParameterMap(request);
    	Map<String, Object> result = new HashMap<>();
		try {
			Entrust entrust=entrustService.getById(param.get("houseId").toString());
			entrust.setEntrustType( param.get("entrustType").toString());
			entrustService.updateEntrustType(entrust);
			User user =(User) session.getAttribute("userModel");
			result = new HashMap<String, Object>();
			User u=userService.getById(user.getUserId());
			result.put("success", true);
			session.setAttribute("userModel", u);
		} catch (Exception e) {
			result.put("success", false);
			e.printStackTrace();
		}
		return result;
    }
    
    @RequestMapping("/getById")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Entrust getById(HttpServletRequest request, HttpServletResponse response,HttpSession session){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		Map<String, Object> result=new HashMap<>();
		try {
			JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
			User user =(User) session.getAttribute("userModel");
			Entrust entrust = json.toJavaObject(Entrust.class);
			
			User u=userService.getById(user.getUserId());
			 return  entrustService.getById(entrust.getHouseId());
		} catch (Exception e) {
			result.put("success", false);
			e.printStackTrace();
			return null;
		}
       
    }
    
    
    /** 根据参数获取 */
    @RequestMapping("/getByParam")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Entrust getByParam(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
		Entrust entrust = json.toJavaObject(Entrust.class);
        return  entrustService.getByParam(entrust);
    }
    
    
    /** 获取列表 */
    @RequestMapping("/getList")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Map<String, Object> getList(HttpServletRequest request, HttpServletResponse response,HttpSession session){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(param));
		Entrust entrust = json.toJavaObject(Entrust.class);
		if( "1".equals(param.get("userIdFlag")) ){
			 User user =(User) session.getAttribute("userModel");
			param.put("userId", user.getUserId());
			entrust.setUserId(user.getUserId());
		}
		Integer pageSize = Integer.parseInt( (String)param.get("pageSize") );
		Integer offset = Integer.parseInt( (String)param.get("offset") );
        return  entrustService.getList(param, pageSize, offset);
    }

	@RequestMapping("upload")
	@ResponseBody
	public Map<String,Object> upload(@RequestParam("files") MultipartFile[] files,
			@RequestParam(value="houseId",required=false) String houseId,HttpServletRequest request,
			HttpSession session) {
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		Entrust entrust=entrustService.getById(houseId);
		List<String> urllist=new ArrayList<>();
		String fileUrl = "";
		String fileTypeStr = "";
		Map<String,Object> result =null;
		// 判断file数组不能为空并且长度大于0
		if (files != null && files.length > 0) {
			// 循环获取file数组中得文件
			for (int i = 0; i < files.length; i++) {
				MultipartFile file1 = files[i];
				try {

					OutputStream os = null;
					InputStream in = null;
					String picPath = null;
					in = file1.getInputStream();
					// 2、保存到临时文件
					// 1K的数据缓冲
					byte[] bs = new byte[1024];
					// 读取到的数据长度
					int len;
					// 输出的文件流保存到本地文件
					File tempFile = new File("/webapp/lanjufile/houseEntruimg");// linux
//					 File tempFile = new File("D:/upFiles/houseimg/");
					if (!tempFile.exists()) {
						tempFile.mkdirs();
					} else {
						LOGGER.info("文件已存在");
					}
//					 String fullPath="D:/upFiles/houseimg/"+file1.getOriginalFilename();
					String fullPath = "/webapp/lanjufile/houseEntruimg/"+ file1.getOriginalFilename();// linux
					String vmURL = "/dataResourceImages/houseEntruimg/"+ file1.getOriginalFilename();
					System.out.println("文件全路径" + fullPath);

					String[] fullPathArr = fullPath.split("\\.");
					fileTypeStr += fullPathArr[fullPathArr.length - 1] + ",";
					os = new FileOutputStream(fullPath);
					// 开始读取
					while ((len = in.read(bs)) != -1) {
						os.write(bs, 0, len);
					}
					os.close();
					in.close();
					urllist.add(vmURL);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		result=saveHouseImg(urllist, entrust);
		// 重定向
		return result;
	}
	
	public Map<String,Object> saveHouseImg(List<String> list,Entrust entrust){
		Map<String,Object> result=new HashMap<>();
		try {
			
			if(list!=null && list.size()>0){
				for(int i=0;i<list.size();i++){
					SnowflakeIdWorker sfw=new SnowflakeIdWorker(2, 1);
					HouseEntrustImg hei=new HouseEntrustImg();
					hei.setCreateTime(new Date());
					hei.setEntrust(entrust);
					hei.setImgId(UUID.randomUUID().toString());
					hei.setType("2");
					hei.setImgUrl(list.get(i).toString());
					entrust.getImgSet().add(hei);
				}
				 entrustService.editHouseEntrust(entrust);
				 result.put("success", true);
			}
		} catch (Exception e) {
			result.put("success", false);
			e.printStackTrace();
		}
		return result;
	}
    @RequestMapping("/updateStatus")
    @ResponseBody
	public Map<String,Object> updateStatus(HttpServletRequest request, HttpServletResponse response){
    	Map<String, Object> param = ServletUtil.getParameterMap(request);
    	Map<String,Object> result=new HashMap<>();
    	Entrust entrust = entrustService.getById(param.get("houseId").toString());
    	entrust.setStatus(param.get("status").toString());
    	 entrustService.editHouseEntrust(entrust);
    	 result.put("success", true);
		return result;
	}
}
